<?php
/*
   Copyright 2012 BiSe Trojanov

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
*/
 require_once('config.php');

?><!doctype html><html>
<head>
 <?php include('./include/header.inc'); ?>
 <title><?php echo $LANGS['edit']['title'].' / '.$sad_domain; ?></title>

 <link rel="stylesheet" href="<?php echo $sad_baseurl; ?>/i/style/edit.css" type="text/css" media="screen">
 <link rel="stylesheet" href="<?php echo $sad_baseurl; ?>/i/style/calendar.css" type="text/css" media="screen">
 <script type="text/javascript" src="<?php echo $sad_baseurl; ?>/i/style/calendar.js"></script>

</head>
<body>
<?php include('./include/toolbar.inc');?>

<?php
// print_r($_GET);
 if (
     ((int)$_GET['id']<1 and $_GET['id']!=='new')
     or strlen($_GET['edit'])<1
     or strlen($_GET['table'])<1
    ){
  echo '`edit` is ';if (strlen($_GET['edit'])>0){echo '<b>not</b> ';}echo 'null<br />';
  echo '`table` is ';if (strlen($_GET['table'])>0){echo '<b>not</b> ';}echo 'null<br />';
?><script>window.close();</script></body></html><?php
  exit;
 }

 $edit=preg_replace('|[/\\\\]|','',$_GET['edit']);

 if (!file_exists($sad_root.'/templates/edit/'.$edit)){
  echo 'Template `'.sad_safe_html($edit).'` from edit is not exists. ';
  if (iamd()){
   echo '<a href="'.$sad_baseurl.'/i/editcode.php?file=edit%2F'.
        urlencode($edit).'" target="_blank">Create</a> him';
  }
  exit;
 }

 if ((int)$_GET['id']>0){
  $q=mysql_query('select * from `'.sad_safe_mysql($sad_prefix.$_GET['table']).
                 '` where `id`='.(int)$_GET['id']);
  if (mysql_error()){
   echo 'This record not found</body></html>';
   exit;
  }
  $q_c=mysql_fetch_assoc($q);
  unset($q);
 }else{
  $q_c=array();
  $q_c['sname'] =$_GET['sname'];
  $q_c['parent']=$_GET['parent'];
 }

/* echo '<link rel="stylesheet" href="'.$sad_baseurl.
      '/i/style/edit.css" type="text/css" media="screen">'."\r\n"; */
 echo '<script src="'.$sad_baseurl.'/i/tiny_mce/tiny_mce.js" type="text/javascript"></script>';
?>

<script>
 tinyMCE.init({
// General options
  mode: "specific_textareas",
  editor_selector : "tinyMCE",
// URL
  convert_urls: false,

  theme : "advanced",
  plugins : "autolink,lists,pagebreak,style,layer,table,save,advhr,advimage,advlink,emotions,iespell,inlinepopups,insertdatetime,preview,media,searchreplace,print,contextmenu,paste,directionality,fullscreen,noneditable,visualchars,nonbreaking,xhtmlxtras,template,wordcount,advlist,autosave,images",
  skin : "o2k7",

// Theme options
  theme_advanced_buttons1 : "save,newdocument,code,|,bold,italic,underline,strikethrough,|,justifyleft,justifycenter,justifyright,justifyfull,styleselect,formatselect,fontselect,fontsizeselect,styleprops",
  theme_advanced_buttons2 : "cut,copy,paste,pastetext,pasteword,|,search,replace,|,bullist,numlist,|,outdent,indent,blockquote,|,undo,redo,|,link,unlink,anchor,image,cleanup,help,|,forecolor,backcolor,|,del,ins",
  theme_advanced_buttons3 : "tablecontrols,|,hr,removeformat,visualaid,|,sub,sup,|,charmap,iespell,media,advhr,|,print,|,ltr,rtl,|,fullscreen,|,images",
  theme_advanced_toolbar_location : "top",
  theme_advanced_toolbar_align : "left",
  theme_advanced_statusbar_location : "bottom",
  theme_advanced_resizing : true,

// tags
  extended_valid_elements: 'noindex',
 });

 function show(tab){
  $('div.form').hide();
  $('#tab'+tab).show();
  $('ul.tabs li').removeClass('active');
  $('#ctab'+tab).addClass('active');
 }

</script><?php

 //scan for additional templates
 $sc  =scandir($sad_root.'/templates/edit/');
 $tabs=array($edit);
 foreach ($sc as $file){
  if (preg_match('|^'.sad_safe_reg($edit).'_|i',$file)){$tabs[count($tabs)]=$file;}
 }
 unset($sc,$file);

 //Caption
 echo "<ul class=\"tabs\">\r\n";
 foreach ($tabs as $tab){
  $button =file_get_contents($sad_root.'/templates/edit/'.$tab);
  preg_match('_^<\\?(php)? *(//|#) *(.*?)( *\\?'.'>)?(\r|\n)_',$button,$a);
  if (strlen($a[3])<1){$a[3]=$tab;}
  echo '<li id="ctab'.$tab.'" class="active"><a href="javascript:" onclick="show(\''.$tab.
       '\');">'.$a[3]."</a>";
  if (iamd()){
   echo '<a href="'.$sad_baseurl.'/i/editcode.php?file=edit%2F'.urlencode($tab).
        '" target="_blank" title="Edit Template"><img src="'.$sad_baseurl.
        '/i/style/receipt--pencil.png" alt="edit template" style="border: none;"></a>';
  }
  echo "</li>\r\n";
 }
 echo '</ul><form method="post" enctype="multipart/form-data" action="'.$sad_baseurl.'/i/edit_post.php">';unset($a);

 $used_sname=false;$used_parent=false;//for new record
 $image_count=-1;
 
 //parse templates
 foreach ($tabs as $tab){
  $button =file_get_contents($sad_root.'/templates/edit/'.$tab);
  $b_s    =preg_split('_(\r|\n)_',$button);
  $pattern='';srand();
  foreach ($b_s as $pat){
   if (preg_match('|^([0-9a-z_-]+) +(\\[(.*?)\\] +)?(.*)$|i',$pat,$a)){
    unset($a[0],$a[2]);$a[3]=preg_replace('|^ *(.*?) *$|','$1',strtolower($a[3]));
    if ($a[1]=='sname'){ $used_sname=true;}
    if ($a[1]=='parent'){$used_parent=true;}
    $t_id=mt_rand(1,10000);

    if ($a[3]==''){//textbox
     $pattern.='<label for="el'.$t_id.'" title="'.sad_safe_html($a[1]).'">'.sad_safe_html($a[4]).
               '</label><input class="textbox" id="el'.$t_id.'" name="'.$a[1].
               '" value="'.sad_safe_html($q_c[$a[1]]).'"><br />'."\r\n";
    }

    if ($a[3]=='simpletext' or $a[3]=='text'){//textarea
     if ($a[3]=='text'){$t='tinyMCE';}else{$t='';}
     $pattern.='<label for="el'.$t_id.'" class="textarea" title="'.sad_safe_html($a[1]).'">'.
               sad_safe_html($a[4]).'</label>';

     if ($a[3]=='text'){
      $pattern.='(<a href="javascript:" onclick="tinyMCE.get(\'el'.
                $t_id.'\').show();" title="Show MCE Tiny">show</a>/'.
                '<a href="javascript:" onclick="tinyMCE.get(\'el'.$t_id.
                '\').hide();" title="Hide MCE Tiny">hide</a>)';
     }
     $pattern.='<br /><textarea class="'.$t.'" id="el'.$t_id.'" name="'.
               sad_safe_html($a[1]).'">'.sad_safe_html($q_c[$a[1]]).
               '</textarea><br />'."\r\n";
    }

    if ($a[3]=='date'){//date
     if (strlen($q_c[$a[1]])<1){$q_c[$a[1]]=time();}
     $pattern.='<label for="el'.$t_id.'" title="'.sad_safe_html($a[1]).'">'.sad_safe_html($a[4]).
               '</label><script>DrawCalendar("'.$t_id.'","'.sad_safe_html($a[1]).
               '",'.(int)($q_c[$a[1]]).');</script><noscript><input class="" id="el'.
               $t_id.'" name="'.$a[1].'" value="'.sad_safe_html($q_c[$a[1]]).
               '"></noscript><br />'."\r\n";
    }

    if ($a[3]=='checkbox'){//checkbox
     if (strlen($q_c[$a[1]])<1){$q_c[$a[1]]=0;}
     $pattern.='<label title="'.sad_safe_html($a[1]).'">'.sad_safe_html($a[4]).
               '</label><input id="el'.$t_id.'_1" name="'.$a[1].
               '" type="radio" style="width: 10px;" value="1"';
     if ($q_c[$a[1]]>0){$pattern.=' checked';}
     $pattern.='><label for="el'.$t_id.'_1" style="width: auto; color: green;">'.
               'On</label><input id="el'.$t_id.'_0" name="'.$a[1].
               '" type="radio" style="width: 10px;" value="0"';
     if ($q_c[$a[1]]<1){$pattern.=' checked';}
     $pattern.='><label for="el'.$t_id.'_0" style="width: auto; color: red;">'.
               "Off</label><br />\r\n";
    }
	
	if ($a[3]=='image'){//image
	 preg_match('_^ *({(.+?)})? *(.+?) *$_',$a[4],$tmp_b);$a[4]=$tmp_b[3];
	 $image_set=array('width'=>10000, 'height'=>10000, 'maxsize'=>50*1024*1024, 'path'=>'', 'nomd5'=>false, 'error'=>'');
	 $image_thumbs=array();$image_count++;
	 preg_match_all('_(\\[(.+?)\\])_',$tmp_b[2],$tmp_c);
	 // thumbs
	 foreach ($tmp_c[2] as $thumb_set){
	  $image_thumb=array('width'=>200,'height'=>200,'path'=>'','prefix'=>'','filetype'=>'jpg');
      $tmp_c  =explode(' ',$thumb_set);$num_num1=0;$num_str1=0;
	  foreach ($tmp_c as $tmp_cs){
       if ($tmp_cs==''){continue;}
	   
	   if (preg_match('_^([0-9]+|auto)$_i', $tmp_cs)){
	    $num_num1++; switch ($num_num1){
	     case 1:$image_thumb['width']  =$tmp_cs;break;
	     case 2:$image_thumb['height'] =$tmp_cs;break;
	     default:$image_set['error'].="Error parse image-tag near `<b>{$tmp_cs}</b>`, invalid count of numeric ".
		                              "in thumb settings #".(count($image_thumbs)+1)."<br />";
	    }
	    continue;
	   }
	   
       if (preg_match('|^"([a-z0-9/._-]*)"$|i', $tmp_cs, $tmp_cs2)){
	    $num_str1++;$tmp_cs2=$tmp_cs2[1];
//		echo "DEBUG: <b>{$num_str1}</b> `".sad_safe_html($tmp_cs2).'`<br>';
		switch ($num_str1){
	     case 1:$image_thumb['path']    =sad_safe_path($tmp_cs2);break;
	     case 2:$image_thumb['prefix']  =sad_safe_path($tmp_cs2);break;
	     case 3:
		  $tmp_cs2=strtolower($tmp_cs2);
		  if ($tmp_cs2=='jpeg'){$tmp_cs2='jpg';}
		  if ($tmp_cs2=='jpg' or $tmp_cs2=='png' or $tmp_cs2=='gif'){
		   $image_thumb['filetype']=$tmp_cs2;
		  }else{
		   $image_set['error'].="Error parse image-tag near `<b>".sad_safe_html($tmp_cs2).
		                        "</b>`, invalid filetype in thumb settings #".(count($image_thumbs)+1).
								", only gif, png, jpg allowed<br />";
		  }
		 break;
	     default:$image_set['error'].="Error parse image-tag near `<b>".sad_safe_html($tmp_cs2).
		           "</b>`, invalid count of string in thumb settings #".(count($image_thumbs)+1)."<br />";
	    }
	    continue;
	   }
	  }
	  $image_thumbs[]=$image_thumb;
	 }
	 
	 $tmp_b[2]=preg_replace('_\\[.+?\\]_','',$tmp_b[2]);
	 $tmp_c   =explode(' ',$tmp_b[2]);$num_num2=0;
	 // main set
	 foreach ($tmp_c as $tmp_cs){
	  if ($tmp_cs==''){continue;}
	  if ($tmp_cs=='nomd5'){$image_set['nomd5']=true;continue;}
	  
	  if (preg_match('_^[0-9]+$_', $tmp_cs)){
	   $num_num2++;
	   switch ($num_num2){
	    case 1:$image_set['width']  =$tmp_cs*1;break;
	    case 2:$image_set['height'] =$tmp_cs*1;break;
	    case 3:$image_set['maxsize']=$tmp_cs*1;break;
	    default:$image_set['error'].="Error parse image-tag near <b>{$tmp_cs}</b>, invalid count of numeric in main settings<br />";
	   }
	   continue;
	  }
	  
	  if (preg_match('|^"([a-z0-9./_-]*)"$|i', $tmp_cs, $tmp_cs2)){
	   $image_set['path']=sad_safe_path($tmp_cs2[1]);
	   continue;
	  }
	 }
	 unset($num_str1, $num_num1, $num_num2, $tmp_c, $tmp_b, $tmp_cs2);
	 
	 //Draw
	 if ($image_set['error']!==''){$pattern.=$image_set['error'];}else{
      $pattern.='<label for="el'.$t_id.'" title="'.sad_safe_html($a[1]).'">'.sad_safe_html($a[4]).
                '</label><input id="el'.$t_id.'" class="textbox" name="opt_image_'.$image_count.
				'_oldvalue" value="'.sad_safe_html($q_c[$a[1]]).'"><input name="opt_image_'.$image_count.
				'_file" type="file"><br />Maxsize <b>'.$image_set['maxsize'].'</b> bytes; Resolution <b>'.
				$image_set['width'].'</b>x<b>'.$image_set['height'].'</b><input type="hidden" name="opt_image_'.
				$image_count.'_name" value="'.$a[1].'"><input type="hidden" name="opt_image_'.$image_count.
				'_width" value="'.$image_set['width'].'"><input type="hidden" name="opt_image_'.$image_count.
				'_height" value="'.$image_set['height'].'"><input type="hidden" name="opt_image_'.$image_count.
				'_path" value="'.$image_set['path'].'"><input type="hidden" name="opt_image_'.$image_count.
				'_size" value="'.$image_set['maxsize'].'">';
      
	  $tmp_b=0;
	  foreach ($image_thumbs as $image_thumb){
	   if (iamd()){$pattern.='; thumb [Resolution <b>'.$image_thumb['width'].'</b>x<b>'.$image_thumb['height'].'</b>; Filetype: <b>'.$image_thumb['filetype'].'</b>] ';}
	   $pattern.='<input type="hidden" name="opt_image_'.$image_count.'_'.$tmp_b.'_width" value="'.
	              $image_thumb['width'].'"><input type="hidden" name="opt_image_'.$image_count.'_'.$tmp_b.
				  '_height" value="'.$image_thumb['height'].'"><input type="hidden" name="opt_image_'.
				  $image_count.'_'.$tmp_b.'_path" value="'.$image_thumb['path'].
				  '"><input type="hidden" name="opt_image_'.$image_count.'_'.$tmp_b.'_prefix" value="'.
	              $image_thumb['prefix'].'"><input type="hidden" name="opt_image_'.$image_count.'_'.$tmp_b.
				  '_filetype" value="'.$image_thumb['filetype'].'">';
	   $tmp_b++;
	  }
	 }
	}//image
	
   }else{
    $pattern.=$pat."\r\n";
   }
  }
  echo '<div class="form" id="tab'.$tab.'">'."\r\n";
  eval('?'.'>'.$pattern.'<'.'?php ');
  echo '</div>';
 }//foreach $tabs
 unset($t_id,$b_s,$button,$pattern,$a,$tab,$tabs);
 
 echo '<input type="submit" class="mrgn nicebutton" value="';
 if (strtolower($_GET['id'])=='new'){echo $LANGS['edit']['add'];}else{echo $LANGS['edit']['edit'];}
 echo '">';

 if (strtolower($_GET['id'])=='new' and !$used_sname){
  echo '<input type="hidden" name="sname"  value="'.sad_safe_html($_GET['sname'])."\">\r\n";
 }
 if (strtolower($_GET['id'])=='new' and !$used_parent){
  echo '<input type="hidden" name="parent" value="'.sad_safe_html($_GET['parent'])."\">\r\n";
 }
?>
<input type="hidden" name="opt_edit"  value="<?php echo sad_safe_html($edit);?>">
<input type="hidden" name="opt_table" value="<?php echo sad_safe_html($_GET['table']);?>">
<input type="hidden" name="opt_id"    value="<?php echo sad_safe_html(strtolower($_GET['id']));?>">
</form>
<?php
 if (strlen($q_c['id'])>0){
?><form action="./delete.php">
<input type="hidden" name="table" value="<?php echo sad_safe_html($_GET['table']); ?>">
<input type="hidden" name="id" value="<?php echo sad_safe_html($q_c['id']); ?>">
<input type="submit" class="mrgn sbm nicebutton" value="<?php echo $LANGS['edit']['delete']; ?>">
</form><?php } ?>
<script>
 show("<?php echo sad_safe_mysql($edit);?>");
 $('.calendar .hidden').hide();
</script>

</body></html>